import json
import os
import time

import jsonpath
import pyttsx3
import requests

CALL = 'master'

def get_city_code(city_name):
    with open('E:\Python37\PYprogram\_city.json','rb') as fp:
        city_date = json.load(fp)
    # print(city_date)
    json_path = '$.[?(@.city_name=="{}")].city_code'.format(city_name)
    # print(json_path)
    city_code = jsonpath.jsonpath(city_date,json_path)
    return city_code[0]
    

def main():
    get_url = 'http://t.weather.sojson.com/api/weather/city/'
    city_name = '巴马县'

    city_code = get_city_code(city_name)
    get_url += str(city_code)
    response = requests.get(url = get_url)

    response.encoding = 'utf-8'
    # print(response.url)
    weather_date = json.loads(response.text)
    shidu = jsonpath.jsonpath(weather_date,'$..shidu')  
    pm25 = jsonpath.jsonpath(weather_date,'$..pm25')  
    data = jsonpath.jsonpath(weather_date,'$..forecast[0].[high,low,ymd,week,type,notice]')
    # print(shidu,pm25,data)
    hour = eval(time.strftime('%H'))
    if 6 <= hour <= 9:
        hour = '早上'
    elif 13 <= hour <=18:
        hour = '下午'
    elif 19 <= hour <=23 or 0 <= hour <= 5:
        hour = '晚上'
    elif 10 <= hour <= 12:
        hour = '上午'
    s = '{}，{}好,今天是{}，{},空气湿度{}，pm2.5为{}，最{}，最{}，天气{}，{}'\
        .format(CALL,hour,data[2],data[3],shidu[0],pm25[0],data[1],data[0],data[-2],data[-1])
    # print(s)

    os.system('cls')
    engine = pyttsx3.init()

    engine.setProperty('rate',150)
    engine.setProperty('volume',200)
    engine.say(s)
    engine.runAndWait()
if __name__ == "__main__":
    main()
